<template>
  <div class="index-container">
    <NavBar :active-index="'1'" />
    <div class="page__cont">
      <el-form
        ref="formRef"
        class="page__form"
        label-position="left"
        label-width="100px"
        :model="form"
        :rules="rules"
      >
        <el-card class="box-card" shadow="never">
          <el-form-item label-width="0">
            <p class="description">
              申报已经执行完毕的代课事项，提交相关领导审批，通过后转交人事部门调整薪酬.
            </p>
          </el-form-item>
          <el-form-item label="事由说明" prop="comment">
            <el-input
              v-model="form.comment"
              maxlength="100"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-card>

        <el-card
          v-for="(row, index) in form.courses"
          :key="`card-${index}`"
          :body-style="{ border: '0px' }"
          class="box-card"
          shadow="never"
        >
          <template #header>
            <div class="card-header">
              <span>
                代课项目{{ form.courses.length > 1 ? index + 1 : '' }}
              </span>
              <div>
                <el-button
                  v-if="form.courses.length > 1"
                  bg
                  :icon="Minus"
                  text
                  @click="minusData(index)"
                />
                <el-button bg :icon="Plus" text @click="addData()" />
              </div>
            </div>
          </template>
          <el-form-item
            label="代课老师"
            :prop="`courses[${index}].tarUserid`"
            :rules="rules.tarUserid"
          >
            <el-button @click="chooseTarUser(row)">选择</el-button>
            <ww-open-data :openid="row.tarUserid" type="userName" />
          </el-form-item>
          <el-form-item
            label="被代老师"
            :prop="`courses[${index}].srcUserid`"
            :rules="rules.srcUserid"
          >
            <el-button @click="chooseSrcUser(row)">选择</el-button>
            <ww-open-data :openid="row.srcUserid" type="userName" />
          </el-form-item>
          <el-form-item
            label="上课日期"
            :prop="`courses[${index}].eventdate`"
            :rules="rules.eventdate"
          >
            <el-date-picker
              v-model="row.eventdate"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item
            label="上课节次"
            :prop="`courses[${index}].coursetime`"
            :rules="rules.coursetime"
          >
            <el-select v-model="row.coursetime">
              <el-option
                v-for="item in coursetimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="年级"
            :prop="`courses[${index}].grade`"
            :rules="rules.grade"
          >
            <el-tree-select v-model="row.grade" :data="gradeOptions" />
          </el-form-item>
          <el-form-item
            label="班级"
            :prop="`courses[${index}].clasz`"
            :rules="rules.clasz"
          >
            <el-select v-model="row.clasz">
              <el-option
                v-for="item in claszOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="学科"
            :prop="`courses[${index}].subject`"
            :rules="rules.subject"
          >
            <el-select v-model="row.subject">
              <el-option
                v-for="item in subjectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-card>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  // import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
  import router from '@/router'
  import NavBar from '../components/NavBar.vue'
  import { useUserStore } from '@/store/modules/user'
  import {
    gradeOptions,
    claszOptions,
    coursetimeOptions,
    subjectOptions,
  } from '@/config'
  import { Plus, Minus } from '@element-plus/icons-vue'
  import { uuid } from '@/utils'
  import { checkRepeat, doEdit } from '@/api/dksb'
  export default defineComponent({
    name: 'Index',
    components: {
      NavBar,
    },
    setup(props, { emit }) {
      const { proxy } = getCurrentInstance()
      const userStore = useUserStore()
      const { corpId, userId } = storeToRefs(userStore)

      console.log(proxy)
      console.log(userId)
      console.log(props, emit)

      const defaultData = {
        srcUserid: '',
        tarUserid: '',
        eventdate: '',
        coursetime: '',
        grade: '',
        clasz: '',
        subject: '',
        hours: 1,
      }

      const state = reactive({
        formRef: null,
        form: {
          id: '',
          corpId: corpId,
          reqUserid: userId,
          comment: '',
          thirdNo: '',
          templateId: 'fa033fe4412e1a3c5d59a49d7e436b8b_406412286',
          courses: [JSON.parse(JSON.stringify(defaultData))],
          status: 0, //0-未提交；1-审批中；2-已通过；3-已驳回；4-已取消
        },
        rules: {
          comment: [{ required: true, trigger: 'blur', message: '请输入事由' }],
          srcUserid: [
            { required: true, trigger: 'blur', message: '请选择被代课教师' },
          ],
          tarUserid: [
            { required: true, trigger: 'blur', message: '请选择代课教师' },
          ],
          eventdate: [
            { required: true, trigger: 'blur', message: '请选择日期' },
          ],
          coursetime: [
            { required: true, trigger: 'blur', message: '请选择日期' },
          ],
          grade: [{ required: true, trigger: 'blur', message: '请选择年级' }],
          clasz: [{ required: true, trigger: 'blur', message: '请选择班级' }],
          subject: [{ required: true, trigger: 'blur', message: '请选择学科' }],
        },
      })

      const shareWx = () => {
        wx.invoke(
          'shareWechatMessage',
          {
            title: '分享标题', // 分享标题
            desc: '分享标题', // 分享描述
            link: 'https://www.baidu.com', // 分享链接
            imgUrl: '', // 分享封面
          },
          function (res) {
            if (res.err_msg == 'shareWechatMessage:ok') {
              console.log('ok....')
            }
          }
        )
      }

      const addData = () => {
        state.form.courses.push(JSON.parse(JSON.stringify(defaultData)))
      }

      const minusData = (index) => {
        state.form.courses.splice(index, 1)
      }

      const chooseSrcUser = (row) => {
        wx.invoke(
          'selectEnterpriseContact',
          {
            fromDepartmentId: -1, // 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
            mode: 'single', // 必填，选择模式，single表示单选，multi表示多选
            type: ['user'], // 必填，选择限制类型，指定department、user中的一个或者多个
            // "selectedDepartmentIds": ["2","3"],// 非必填，已选部门ID列表。用于多次选人时可重入，single模式下请勿填入多个id
            // "selectedUserIds": ["lisi","lisi2"]// 非必填，已选用户ID列表。用于多次选人时可重入，single模式下请勿填入多个id
          },
          function (res) {
            if (res.err_msg == 'selectEnterpriseContact:ok') {
              if (typeof res.result == 'string') {
                res.result = JSON.parse(res.result) //由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
              }
              if (res.result.userList.length > 0) {
                row.srcUserid = res.result.userList[0].id
              }
            }
          }
        )
      }
      const chooseTarUser = (row) => {
        wx.invoke(
          'selectEnterpriseContact',
          {
            fromDepartmentId: -1, // 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
            mode: 'single', // 必填，选择模式，single表示单选，multi表示多选
            type: ['user'], // 必填，选择限制类型，指定department、user中的一个或者多个
            // "selectedDepartmentIds": ["2","3"],// 非必填，已选部门ID列表。用于多次选人时可重入，single模式下请勿填入多个id
            // "selectedUserIds": ["lisi","lisi2"]// 非必填，已选用户ID列表。用于多次选人时可重入，single模式下请勿填入多个id
          },
          function (res) {
            if (res.err_msg == 'selectEnterpriseContact:ok') {
              if (typeof res.result == 'string') {
                res.result = JSON.parse(res.result) //由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
              }
              if (res.result.userList.length > 0) {
                row.tarUserid = res.result.userList[0].id
              }
            }
          }
        )
      }

      const getCourseDesc = (course) => {
        const { eventdate, grade, clasz, coursetime, subject } = course
        return `${getOptLabel(
          subjectOptions,
          subject
        )} ${eventdate} ${getOptLabel(
          coursetimeOptions,
          coursetime
        )} ${getOptLabel(gradeOptions, grade)} ${getOptLabel(
          claszOptions,
          clasz
        )} `
      }

      const getOptLabel = (options, value) => {
        let label = ''
        options.some((op) => {
          if (op.value === value) {
            label = op.label
            return true
          }
          if (op.children) {
            label = getOptLabel(op.children, value)
            if (label) return true
          }
        })
        return label
      }

      const onSubmit = async () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            let thirdNo = 'dksb' + uuid(6) + new Date().getTime()
            state.form.thirdNo = thirdNo
            const { templateId, comment, courses } = state.form
            const list = courses.map((course, index) => {
              return {
                title: `代课申报${courses.length > 1 ? index + 1 : ''}`,
                type: 'text',
                value: getCourseDesc(course),
              }
            })
            const fieldList = [
              {
                title: '代课说明',
                type: 'text',
                value: comment,
              },
              ...list,
              {
                title: '申报详情链接',
                type: 'link',
                value: `http://wx.xerllent.cn/dksb#history/${thirdNo}`,
              },
            ]
            // console.log(fieldList)

            //检查代课数据是否重复
            checkRepeat(state.form)
              .then((res) => {
                console.log(res)
                wx.invoke(
                  'thirdPartyOpenPage',
                  {
                    oaType: '10001', // String
                    templateId, // String
                    thirdNo, // String
                    extData: {
                      fieldList,
                    },
                  },
                  function (res) {
                    // 输出接口的回调信息
                    console.log('thirdPartyOpenPage:', res)
                    if (res.err_msg == 'thirdPartyOpenPage:ok') {
                      doEdit(state.form)
                        .then(({ data }) => {
                          state.form.id = data.id
                          state.form.courses.map((c) => {
                            c.dksbId = data.id
                          })
                          router
                            .push({ path: '/history', replace: true })
                            .then(() => {})
                        })
                        .catch((e) => {
                          console.log(e)
                        })
                    }
                  }
                )
              })
              .catch((e) => {
                console.log(e)
              })
          }
        })
      }

      return {
        ...toRefs(state),
        shareWx,
        chooseSrcUser,
        chooseTarUser,
        gradeOptions,
        claszOptions,
        coursetimeOptions,
        subjectOptions,
        Plus,
        Minus,
        addData,
        minusData,
        onSubmit,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .index-container {
    .page__form {
      max-width: 800px;
      margin: 0 auto;
      .box-card {
        border: 0;
      }
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .description {
        color: darkgrey;
        font-family: serif;
        font-size: 14px;
      }
    }
  }
</style>
